package com.wgt.startx.helper;

import com.wgt.startx.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by wgt on 2017/7/30.
 */
public class BeanHelper {
    private static final Map<Class<?>,Object> BEAN_MAP = new HashMap<Class<?>, Object>();


    /**
     *用于Bean映射 (存放Bean类与Bean是实例映射关系)
     */
    static {
        Set<Class<?>> classSet = ClassHelper.getClassSet();
        for(Class<?> cls:classSet){
            Object obj = ReflectionUtil.instanceObj(cls);
            BEAN_MAP.put(cls,obj);
        }
    }

    /**
     * 获取bean映射
     * @return
     */
    public static Map<Class<?>,Object> getBeanMap(){
        return BEAN_MAP;
    }

    /**
     * 获取bean实例
     */
    public static <T>T getBean(Class<T> clazz){
        if (clazz==null)throw new NullPointerException();
        if (!BEAN_MAP.containsKey(clazz)){
            throw new RuntimeException("can not get bean by class:"+clazz);
        }
        return (T)BEAN_MAP.get(clazz);
    }
 }
